﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using Microsoft.LightSwitch;
using System.Xml.Linq;
using System.Xml.Xsl;
using System.Xml;

namespace LightSwitchApplication
{
    public partial class DownloadFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get parameters
            Request.ContentEncoding = System.Text.Encoding.Unicode;

            string VisitId = Request.QueryString["VisitId"];

            // All parameters must have a value or return nothing
            if (!string.IsNullOrEmpty(VisitId))
            {
                try
                {
                    //string path = MapPath(@"~\");               
                    string VisitTimeFrom = Utils.SimpleDecoder(Request.QueryString["VisitTimeFrom"]);
                    string VisitTimeTo = Utils.SimpleDecoder(Request.QueryString["VisitTimeTo"]);
                    string ShopContactEmail = Utils.SimpleDecoder(Request.QueryString["ShopContactEmail"]);
                    string ShopName = Utils.SimpleDecoder(Request.QueryString["ShopName"]);
                    string ShopFullAddress = Utils.SimpleDecoder(Request.QueryString["ShopFullAddress"]);
                    string SalesPersonContactEmail = Utils.SimpleDecoder(Request.QueryString["SalesPersonContactEmail"]);
                    string VisitDescription = Utils.SimpleDecoder(Request.QueryString["VisitDescription"]);
                    string SalesPersonName = Utils.SimpleDecoder(Request.QueryString["SalesPersonName"]); 

                    //// Find instance of "bin"
                    //int intPositionOfBin = path.ToLower().IndexOf("bin");
                    //if (intPositionOfBin > -1)
                    //{
                    //    path = path.Substring(0, intPositionOfBin);
                    //}

                    //path = path + @"Files\";

                    //// Remove any .. to prevent backing up directories
                    //VisitId = VisitId.Replace("..", ""); 
                    //string strPath = Path.Combine(path, VisitId);

                    // Return the file
                    Response.ClearHeaders();
                    Response.AddHeader("content-disposition", string.Format("attachment; filename=visit_{0}.ics", VisitId));

                    Response.ClearContent();
                    Response.ContentEncoding = System.Text.Encoding.Unicode;
                    Response.ContentType = GetContentType(".ics");

                    //FileStream sourceFile = new FileStream(strPath, FileMode.Open);
                    //long FileSize;
                    //FileSize = sourceFile.Length;
                    //byte[] getContent = new byte[(int)FileSize];
                    //sourceFile.Read(getContent, 0, (int)sourceFile.Length);
                    //sourceFile.Close();

                    //Response.BinaryWrite(getContent);
                    StringWriter wr = new StringWriter();
                    //using (var dwspace = new DataWorkspace())
                    {
                        //Visit visit = dwspace.ApplicationData.Visits.Where(v => v.Id.ToString() == VisitId).FirstOrDefault();
                        //Visit visit = LightSwitchApplication.Server.DataAccess.GetVisitData(VisitId);

                        //if (visit == null) return;
                        #region build text
                        wr.WriteLine("BEGIN:VCALENDAR");
                        wr.WriteLine("PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN");
                        wr.WriteLine("VERSION:2.0");
                        wr.WriteLine("METHOD:REQUEST");
                        wr.WriteLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE");
                        wr.WriteLine("BEGIN:VTIMEZONE");
                        wr.WriteLine("TZID:Europe/Kiev"); //this is a key moment for your customers in Ukraine only! 
                        wr.WriteLine("BEGIN:STANDARD");
                        wr.WriteLine("RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4");
                        //wr.WriteLine("TZOFFSETFROM:+0200");
                        //wr.WriteLine("TZOFFSETTO:+0200");
                        wr.WriteLine("END:STANDARD");
                        //wr.WriteLine("BEGIN:DAYLIGHT");
                        //wr.WriteLine("RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=10");
                        ////wr.WriteLine("TZOFFSETFROM:+0930");
                        ////wr.WriteLine("TZOFFSETTO:+1030");
                        //wr.WriteLine("END:DAYLIGHT");
                        wr.WriteLine("END:VTIMEZONE");
                        wr.WriteLine("BEGIN:VEVENT");
                        if (!string.IsNullOrEmpty(SalesPersonContactEmail))
                        {
                            wr.WriteLine("ATTENDEE;CN=" + SalesPersonContactEmail);
                            if (!string.IsNullOrEmpty(ShopContactEmail))
                                wr.Write(";RSVP=TRUE:" + ShopContactEmail);
                        }
                        wr.WriteLine("CLASS:PUBLIC");
                        wr.WriteLine("CREATED:" + DateTime.Now.AddHours(-2).ToString("yyyyMMddThhmm00Z")); //time offset for servers in West Europe ???
                        wr.WriteLine("DTSTART:" + VisitTimeFrom);
                        if (!string.IsNullOrEmpty(VisitTimeTo))
                            wr.WriteLine("DTEND:" + VisitTimeTo);
                        wr.WriteLine("DTSTAMP:" + DateTime.Now.ToString("yyyyMMddThhmm00"));
                        wr.WriteLine("DESCRIPTION:" + VisitDescription);
                        wr.WriteLine("LAST-MODIFIED:20120321T112208Z");

                        if (!string.IsNullOrEmpty(ShopFullAddress))
                            wr.WriteLine("LOCATION;LANGUAGE=ru:" + ShopFullAddress);

                        wr.WriteLine("ORGANIZER;LANGUAGE=ru;CN=\"" + SalesPersonName + "\":mailto:" + SalesPersonContactEmail);
                        wr.WriteLine("PRIORITY:5");
                        wr.WriteLine("SEQUENCE:0");
                        wr.WriteLine("SUMMARY;LANGUAGE=ru:Посетить магазин " + ShopName);
                        wr.WriteLine("TRANSP:OPAQUE");
                        wr.WriteLine("UID:" + Guid.NewGuid().ToString().Replace("-", ""));
                        wr.WriteLine("X-ALT-DESC;FMTTYPE=text/html:<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2//E");
                        wr.WriteLine("N\">\\n<HTML>\\n<HEAD>\\n<META NAME=\"Generator\" CONTENT=\"MS Exchange Server version 14.02.5004.000\">\\n<TITLE></TITLE>\\n</HEAD>\\n<BODY>\\n<!-- Converted from text/rtf format -->\\n\\n<P DIR=LTR><SPAN LANG=\"ru\"></SPAN><SPAN LANG=\"ru\"><FONT FACE=\"Calibri\">"
                            + VisitDescription + "</FONT></SPAN><SPAN LANG=\"ru\"></SPAN><SPAN LANG=\"ru\"></SPAN></P>\\n\\n</BODY>\\n</HTML>");
                        wr.WriteLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY");
                        wr.WriteLine("X-MICROSOFT-CDO-IMPORTANCE:1");
                        wr.WriteLine("X-MICROSOFT-DISALLOW-COUNTER:FALSE");
                        wr.WriteLine("X-MS-OLK-AUTOFILLLOCATION:FALSE");
                        wr.WriteLine("X-MS-OLK-AUTOSTARTCHECK:FALSE");
                        wr.WriteLine("X-MS-OLK-CONFTYPE:0");
                        wr.WriteLine("END:VEVENT");
                        wr.WriteLine("END:VCALENDAR");
                    }


                        #endregion
                    wr.Close();
                    Response.Write(wr);
                    Response.Flush();
                    Response.Close();

                }
                catch (Exception ex)
                {
                    lblDisplayFilesError.Text = ex.Message;
                }
            }
            else 
            {
                string id = Request.QueryString["OrderId"];
                string xml = Utils.SimpleDecoder(Request.QueryString["src"]);

                if (!string.IsNullOrEmpty(id) && !string.IsNullOrEmpty(xml))
                {
                    try
                    {
                        Response.ClearHeaders();
                        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.html", id));

                        Response.ClearContent();
                        Response.ContentEncoding = System.Text.Encoding.Unicode;
                        Response.ContentType = GetContentType("html");

                        XDocument xmlDoc = XDocument.Load(new StringReader(xml));
                        XslCompiledTransform xslt = new XslCompiledTransform();
                        //string xslString = LightSwitchApplication.Server.DataAccess.GetSystemParameterValue(@"SalesOrder.StyleSheet");
                        //if (!string.IsNullOrEmpty(xslString))
                        //{
                        //    XDocument xslDoc = XDocument.Load(new StringReader(xslString));
                        //    xslt.Load(xslDoc.CreateReader());
                        //}
                        //else
                        //{
                            xslt.Load("SalesOrder.xsl");
                        //}

                        using (MemoryStream stream = new MemoryStream())
                        {
                            using (var writer = XmlWriter.Create(stream, xslt.OutputSettings))
                            {
                                xslt.Transform(xmlDoc.CreateReader(), writer);
                            };
                            var arr = stream.ToArray();
                            Response.Write(xslt.OutputSettings.Encoding.GetString(arr));
                        }
                        Response.End();
                    }
                    catch (Exception ex)
                    {
                        lblDisplayFilesError.Text = ex.Message;
                    }
                }

            }

        }

        #region GetContentType
        public string GetContentType(string strextension)
        {
            if (!strextension.StartsWith("."))
                strextension = "." + strextension;

            string contentType;
            switch (strextension.ToLower())
            {
                case ".gif":
                    contentType = "image/gif";
                    break;
                case ".jpg":
                case ".jpeg":
                    contentType = "image/jpeg";
                    break;
                case ".png":
                    contentType = "image/png";
                    break;
                case ".doc":
                    contentType = "application/ms-word";
                    break;
                case ".docx":
                    contentType = "application/vnd.ms-word.document.12";
                    break;
                case ".pdf":
                    contentType = "application/pdf";
                    break;
                case ".xls":
                    contentType = "application/vnd.ms-excel";
                    break;
                case ".ppt":
                    contentType = "application/vnd.ms-powerpoint";
                    break;
                case ".zip":
                    contentType = "application/zip";
                    break;
                case ".html":
                case ".htm":
                    contentType = "text/html";
                    break;
                case ".xml":
                case ".txt":
                case ".ics":
                    contentType = "text/plain";
                    break;
                default:
                    contentType = "application/octet-stream";
                    break;
            }
            return contentType;
        }
        #endregion
    }
}